'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: middleware.py
* @Time: 2025/10/10
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from typing import Optional

from flask import Request
from injector import inject

from internal.exception.exception import UnauthorizedException
from internal.model import Account
from internal.service import AccountService
from internal.service.jwt_service import JwtService


@inject
@dataclass
class Middleware:
    """应用中间件， 可以重写request与 unauthorized_handler"""
    jwt_service:JwtService
    account_service:AccountService
    def request_loader(self, request:Request)->Optional[Account]:
        #1、单独为llmops路由蓝图创建请求加载器
        if request.blueprint == "llmops-ai-platform":
            #2、提取请求头的header信息
            auth_header = request.headers.get("Authorization")
            if not  auth_header:
                raise UnauthorizedException("该接口需要授权后才能访问！")
            #3、请求信息中没有空格分隔符则校验失败
            if " " not in auth_header:
                raise UnauthorizedException("该接口授权失败，授权格式为 bearer key!!")
            #4、分割授权信息必须符合Bearer  access_token格式
            auth_schema, access_token = auth_header.split(None,1)

            if auth_schema.lower() != "bearer":
                raise UnauthorizedException("该接口需要授权， 格式验证失败！")
            #5、解析token 信息得到用户信息并返回
            payload = self.jwt_service.parse_token(access_token)
            account_id = payload.get("sub")
            return self.account_service.get_account(account_id)

        else:
            return None
